package com.dna.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dna.entity.UserEntity;
import com.dna.mapper.UserMapper;
import com.dna.service.UserService;
import com.dna.utils.Constant.UserState;
import com.dna.utils.Query;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import tk.mybatis.mapper.entity.Example;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserEntity queryById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public UserEntity queryOne(UserEntity user) {
        return userMapper.selectOne(user);
    }

    @Override
    public List<UserEntity> queryAll() {
        return userMapper.selectAll();
    }

    @Override
    public List<UserEntity> queryList() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public PageInfo<UserEntity> queryPageList(Query<UserEntity> q) {

        PageHelper.startPage(q.getPage(), q.getLimit());
        UserEntity userEntity = q.getT();
        userEntity.setState(UserState.NORMAL.getValue());
        List<UserEntity> userList = userMapper.selectList(userEntity);
        return new PageInfo<UserEntity>(userList);
    }

    @Override
    @Transactional
    public void save(UserEntity user) {
        userMapper.insertSelective(user);
    }

    @Override
    @Transactional
    public void update(UserEntity user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    @Transactional
    public void delete(UserEntity user, Example example) {
        userMapper.updateByExampleSelective(user, example);
    }

    @Override
    @Transactional
    public int updatePassword(Long userId, String password, String newPassword) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("password", password);
        map.put("newPassword", newPassword);
        return userMapper.updatePassword(map);
    }
}
